<template>
  <div class="ticletAppy p-2">
    <el-card>
      <div class="card-header">
        <div class="one">业务系统</div>
      </div>
      <div class="mt-[25px]">
        <el-form ref="ruleFormRef" :model="queryParams" :inline="true">
          <el-form-item label="创建时间" style="width: 408px">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="批次号" prop="no" label-width="70">
            <el-input v-model="queryParams.no" placeholder="请输入批次号" clearable style="width: 300px" />
          </el-form-item>
          <el-form-item label="服务商名称" label-width="82" prop="syd_name" v-if="!contentType">
            <el-input v-model="queryParams.syd_name" placeholder="请输入服务商名称" clearable style="width: 300px" />
          </el-form-item>
          <el-form-item label="产品编号" prop="proNo" v-if="!contentType">
            <el-input v-model="queryParams.proNo" placeholder="请输入产品编号" clearable style="width: 300px" />
          </el-form-item>

          <el-form-item label="业务类型" prop="busType" label-width="70" v-if="!contentType">
            <el-select v-model="queryParams.busType" placeholder="请选择业务类型" clearable style="width: 270px">
              <el-option v-for="dict in sys_busType_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="发票类型" prop="invoiceType" label-width="70" v-if="!contentType">
            <el-select v-model="queryParams.invoiceType" placeholder="请选择发票类型" clearable style="width: 270px">
              <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="服务费承担方" prop="serviceChargeType" label-width="100" v-if="!contentType">
            <el-select v-model="queryParams.serviceChargeType" placeholder="请选择服务费承担方" clearable style="width: 270px">
              <el-option v-for="dict in syn_serviceChargeType" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="waycanInvoicingList(true)">搜索</el-button>
            <el-button type="primary" icon="Refresh" @click="resetForm(ruleFormRef)">重置</el-button>
            <a class="btn-nav" @click="contentType = !contentType">
              <span v-if="contentType"
                >高级模式
                <i data-v-771b1fc0="" aria-label="图标: down" class="anticon anticon-down"
                  ><svg
                    viewBox="64 64 896 896"
                    data-icon="down"
                    width="1em"
                    height="1em"
                    fill="currentColor"
                    aria-hidden="true"
                    focusable="false"
                    class=""
                  >
                    <path
                      d="M884 256h-75c-5.1 0-9.9 2.5-12.9 6.6L512 654.2 227.9 262.6c-3-4.1-7.8-6.6-12.9-6.6h-75c-6.5 0-10.3 7.4-6.5 12.7l352.6 486.1c12.8 17.6 39 17.6 51.7 0l352.6-486.1c3.9-5.3.1-12.7-6.4-12.7z"
                    ></path></svg></i
              ></span>
              <span v-if="!contentType"
                >精简模式
                <i data-v-771b1fc0="" aria-label="图标: up" class="anticon anticon-up"
                  ><svg
                    viewBox="64 64 896 896"
                    data-icon="up"
                    width="1em"
                    height="1em"
                    fill="currentColor"
                    aria-hidden="true"
                    focusable="false"
                    class=""
                  >
                    <path
                      d="M890.5 755.3L537.9 269.2c-12.8-17.6-39-17.6-51.7 0L133.5 755.3A8 8 0 0 0 140 768h75c5.1 0 9.9-2.5 12.9-6.6L512 369.8l284.1 391.6c3 4.1 7.8 6.6 12.9 6.6h75c6.5 0 10.3-7.4 6.5-12.7z"
                    ></path></svg></i
              ></span>
            </a>
          </el-form-item>
        </el-form>
      </div>
      <div class="messcolor">
        <p class="ptext">
          申请发票说明： <br />
          1.单张发票最高限额为10万元，同一产品编号同一开票类目总金额低于10万元的订单，请您合并申请发票。您的发票申请，平台服务商会在5个工作日内受理；<br />
          2.每月25号前提交的开票申请当月可以正常出票；25号后提交的开票申请将于次月月初出票；<br />
          3.提交开票申请时选择的开票类目需与业务合同保持一致，下拉选择的开票类目如果没有匹配的，请选择相近的类目或在【备注】里填写具体需求；特殊类目<br />
          需要填写发票备注栏的，请在【发票备注栏】里填写需要备注的内容；<br />
          4.平台部分服务商可以开电子发票，如需电子发票请先到【开票信息维护】菜单维护发票接收邮箱，并在【备注】输入框备注电子专票/普票。<br />
          5.当您收到纸质发票后，请登录平台签收发票。<br />
        </p>
        <div class="invoice-info">
          <el-button type="primary" @click="waymergeopen">合并申请发票</el-button>
          <p class="infotext">
            已选择<span>{{ multipleSelection.length }}</span
            >项目
          </p>
          <el-link type="primary" @click="handSelectAll()">清空</el-link>
          <el-link type="primary" @click="handSelectAll(invoiceBoll)">全选</el-link>
        </div>
      </div>
      <div class="towtabbal mt-[20px]">
        <el-table ref="multipleTableRef" v-loading="loading" border :data="invoiceBoll" style="width:100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="创建时间" align="center" prop="addTime" width="180" />
          <el-table-column label="批次号" align="center" prop="no" width="220" show-overflow-tooltip />
          <el-table-column label="服务商名称" align="center" prop="sydName" width="220" show-overflow-tooltip />
          <el-table-column label="业务类型" align="center" width="120">
            <template #default="scope">
              <div>
                <span v-if="scope.row.busType == 1">委托代征</span>
                <span v-else-if="scope.row.busType == 2">自然人代开</span>
                <span v-else-if="scope.row.busType == 3">个体户注册</span>
                <span v-else-if="scope.row.busType == 4">临时税务登记</span>
                <span v-else-if="scope.row.busType == 5">资金代发</span>
                <span v-else-if="scope.row.busType == 6">派遣&外包</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="产品编号" align="center" prop="proNo" width="160" show-overflow-tooltip />
          <el-table-column label="发票类型" align="center" prop="invoiceType" width="140">
            <template #default="scope">
              <div>
                <span v-if="scope.row.invoiceType == 1">增值税专用发票</span>
                <span v-else-if="scope.row.invoiceType == 2">增值税普通发票</span>
                <span v-else-if="scope.row.invoiceType == 3">差额票</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="开票金额（元）" align="center" width="120" prop="amountEnt" >
            <template #default="scope">
                {{proxy?.convertFenToYuan(scope.row.amountEnt)}}
            </template>
          </el-table-column>
          <el-table-column label="服务费（元）" align="center" width="120" prop="serviceChargeAmount" >
            <template #default="scope">
                  {{proxy?.convertFenToYuan(scope.row.serviceChargeAmount)}}
              </template>
            </el-table-column>
          <el-table-column label="开票状态" align="center">
            <template #default="scope">
              <div>
                <span v-if="scope.row.isInvoice == 0">待开票</span>
                <span v-else-if="scope.row.isInvoice == 1">已开票</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="业务备注" align="center" prop="remark" width="120" show-overflow-tooltip />
          <el-table-column fixed="right" label="操作" align="center" prop="roleName" width="130">
            <template #default="scope">
              <el-button type="success" plain size="small" @click="selectionFapiao(scope)">申请发票</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="demo-pagination-block mt-[20px]">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :small="true"
          :disabled="false"
          :background="false"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="waycanInvoicingList"
          @current-change="waycanInvoicingList"
        />
      </div>
    </el-card>
    <!-- 开发票弹窗 -->
    <el-dialog v-model="dialogVisible" title="申请发票" width="800" :close-on-click-modal="false" @close="wayclosedialog" @open="wayopenDialog">
      <div class="dialog-content">
        <div class="dialog-content-box">
          <div>
            <p>批次订单总数：{{invPagenumber}}笔</p>
            <p>发票抬头：{{formDing.header}}</p>
            <p>开户银行：{{formDing.bankAddress}}</p>
            <p>单位注册地址：{{ formDing.unitAddress }}</p>
            <p>邮箱：{{ formDing.email }}</p>
          </div>
          <div>
            <p>批次订单总金额(元)：{{proxy?.convertFenToYuan(invAmount)}}</p>
            <p>纳税人识别号：{{ formDing.nsrSbh }}</p>
            <p>银行账号：{{ formDing.bankCard }}</p>
            <p>单位电话：{{ formDing.unitPhone }}</p>
            <p>开票类型：{{ invtype }}</p>
          </div>
        </div>
        <div class="mt-[20px]">
          <el-form
            ref="ruleFormRefform"
            style="max-width: 500px;margin:0 auto"
            :model="ruleForm"
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
            v-loading="loadingBd"
            status-icon
          >
            <el-form-item label="收件人:" prop="name">
              <el-input v-model="ruleForm.name" required />
            </el-form-item>
            <el-form-item label="收件人电话:" prop="phone">
              <el-input v-model="ruleForm.phone" required />
            </el-form-item>
            <el-form-item label="收件人地址:" prop="address">
              <el-input v-model="ruleForm.address" required />
            </el-form-item>
            <el-form-item label="开票类型:" prop="invtypeNum">
              <el-select v-model="ruleForm.invtypeNum" placeholder="请选择开票类型"  style="width:100%">
                <el-option v-for="dict in sys_invtype_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="开票项目:" prop="type">
              <!--
              <el-select v-model="ruleForm.type" placeholder="请选择开票项目" style="width:100%">
                <el-option :label="item.type" :value="item.id" v-for="(item,index) in invoiceTypeList" :key="index" />
              </el-select>-->

              <el-cascader ref="cascaderRef" :options="invoiceTypeList" :props="props1"  v-model="ruleForm.type" style="width:100%"
                 placeholder="请选择开票类目" clearable  :show-all-levels="false" :collapse-tags="true" />
            </el-form-item>
            <el-form-item label="发票备注栏:">
              <el-input v-model="ruleForm.invRemark" type="textarea" placeholder="请输入发票备注栏" />
            </el-form-item>
            <el-form-item label="备注:">
              <el-input v-model="ruleForm.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-form>
        </div>
        <el-row justify="center">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRefform)">确定</el-button>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, toRefs, reactive, onMounted } from 'vue';
import { canInvoicingList, invoiceTypetypes, paymentinvoice } from '@/api/invoice/TicketApply/index';
import { invoiceAddress } from '@/api/invoice/TicketInfo/index';

import type { FormInstance } from 'element-plus';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;


// 完税证明上传状态选择
const sys_invtype_disable = ref([
  {
    value: 1,
    label: '增值税专用发票'
  },{
    value: 2,
    label: '增值税普通发票'
  }
])


const data = reactive({
  queryParams: {
    begin_time: '',
    end_time: '',
    no: '',
    busType: '',
    syd_name: '',
    proNo: '',
    serviceChargeType: '',
    invoiceType: '',
    pageSize: 10,
    pageNum: 1
  }
});
const { queryParams } = toRefs(data);
const contentType = ref(true); // true 精简模式 , false 高级模式
const dateRange = ref<[DateModelType, DateModelType]>(['', '']); //创建时间参数
const dialogVisible = ref(false); //申请发票弹窗
const multipleTableRef = ref();
const ruleFormRefform = ref();
const cascaderRef = ref();
const props1= ref({ multiple: false,emitPath:false })
//校验
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!');


      waypaymentinvoice();
    } else {
      console.log('error submit!', fields);
    }
  });
};

//新增发票状态
const loadingBd = ref(false); //加载动画
const waypaymentinvoice = async () => {
  loadingBd.value = true;
  let obj = {
    header: formDing.value.header,
    type: invtypeNum.value,
    type: ruleForm.value.invtypeNum,
    creditCode: formDing.value.nsrSbh,
    bankAddress: formDing.value.bankAddress,
    bankCard: formDing.value.bankCard, //开户银行账号
    category: ruleForm.value.type, //开票类目
    addId: formDing.value.id, //收件地址id
    addName: ruleForm.value.name, //收件人姓名
    addPhone: ruleForm.value.phone, //收件人手机号
    addAddress: ruleForm.value.address, //收件地址
    addEmail: formDing.value.email, //邮箱地址
    invRemark: ruleForm.value.invRemark, //发票备注栏
    remark: ruleForm.value.remark, //备注
    dwzcdz: formDing.value.unitAddress, //单位注册地址
    dwdh: formDing.value.unitPhone, //单位电话
    sydId: fapiaoList.value[0].sydId, //结算中心id
    sydNo: fapiaoList.value[0].sydNo, //结算中心编号
    opNo: fapiaoList.value[0].opNo, //运营商编号
    opId: fapiaoList.value[0].opId, //运营商id,
    channelId: fapiaoList.value[0].channelId, //代理商id
    channelNo: fapiaoList.value[0].channelNo, //代理商编号
    channelCode: fapiaoList.value[0].channelCode, //代理商上下级关系编码
    merId: fapiaoList.value[0].merId, //商户id
    merNo: fapiaoList.value[0].merNo, //商户编号
    busType: fapiaoList.value[0].busType, //业务类型
    bills: []
  };

  let selNodes = cascaderRef.value.getCheckedNodes(true);
  let invoceNames:any = [];
  if(selNodes){
    selNodes.forEach(item=>{
      invoceNames.push(item.data.label);
    })
  }
  obj.category = invoceNames.join(",");

  fapiaoList.value.forEach((eitem) => {
    let dobject = {
      invAmount: eitem.amountEnt,
      money: eitem.money,
      serviceChargeAmount: eitem.serviceChargeAmount,
      taskId: eitem.taskId,
      taskNo: eitem.taskNo,
      billId: eitem.id,
      billNo: eitem.no
    };
    obj.bills.push(dobject);
  });
  console.log('obj', obj);
  const res = await paymentinvoice(obj).finally(() => {
    console.log('请求完成');
    dialogVisible.value = false;
    loadingBd.value = false;
    multipleTableRef.value!.clearSelection();
  });
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: '开票申请成功'
    });
  }
  waycanInvoicingList(true);
};

// 弹窗关闭事件
const wayclosedialog = () => {
  fapiaoList.value = [];
  ruleForm.value.invRemark = '';
  ruleForm.value.remark = '';
};
const wayopenDialog = () => {
  wayinvoiceTypetypes();
};
// 获取表单数据
const formDing = ref({});
const wayinvoiceAddress = async () => {
  const res = await invoiceAddress({
    pageSize: 10,
    pageNum: 1
  });
  console.log('formDing', res.rows[0]);
  if (res.total > 0) {
    formDing.value = res.rows[0];
    ruleForm.value.name = res.rows[0].name;
    ruleForm.value.phone = res.rows[0].phone;
    ruleForm.value.address = res.rows[0].address;
  }
};

const ruleForm = ref({
  name: '',
  phone: '',
  address: '',
  type: '',
  invtypeNum:null,
  remark: '',
  invRemark: ''
});


// 申请发票管理
const invAmount = ref(0); //总金额
const invPagenumber = ref(0); //选择总数
const invtype = ref(''); //类型
const invtypeNum = ref();
const fapiaoList = ref([]); //选中开发票的数据列表
const selectionFapiao = (event) => {
  const isDuplicate = fapiaoList.value.some((obj) => obj.id === event.row.id);
  if (!isDuplicate) {
    fapiaoList.value.push(event.row);
  }
  invAmount.value = fapiaoList.value[0].amountEnt;
  invPagenumber.value = fapiaoList.value.length;
  if (event.row.invoiceType == 1) {
    invtype.value = '增值税专用发票';
    invtypeNum.value = 1;
    ruleForm.value.invtypeNum = 1;
  } else if (event.row.invoiceType == 2) {
    invtype.value = '增值税普通发票';
    invtypeNum.value = 2;
    ruleForm.value.invtypeNum = 2;
  } else if (event.row.invoiceType == 3) {
    invtype.value = '差额票';
    invtypeNum.value = 3;
    ruleForm.value.invtypeNum = 3;
  }
  dialogVisible.value = true;
  console.log('multipleTableRef', fapiaoList.value);
};

// 重设
const ruleFormRef = ref();
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dateRange.value = ['', ''];
  queryParams.pageNum = 1;
  waycanInvoicingList();
};
// 合并申请发票
const waymergeopen = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage('请先选择要合并开票的订单');
  } else {
    let muklist = multipleSelection.value.every((element) => element.proNo === multipleSelection.value[0].proNo);
    if (muklist) {
      console.log('都一样');
      fapiaoList.value.push(...multipleSelection.value);
      let amount = 0;
      multipleSelection.value.forEach(ele=>{
        amount = amount+ele.amountEnt;
      })

      if(amount > 10000000){
        ElMessage.error("总金额不能超过10万元");
        return ;
      }
      // invAmount.value = fapiaoList.value[0].amountEnt;
       invAmount.value = amount;
      invPagenumber.value = fapiaoList.value.length;
      if (multipleSelection.value[0].invoiceType == 1) {
        invtype.value = '增值税专用发票';
        invtypeNum.value = 1;
        ruleForm.value.invtypeNum = 1;
      } else if (multipleSelection.value[0].invoiceType == 2) {
        invtype.value = '增值税普通发票';
        invtypeNum.value = 2;
        ruleForm.value.invtypeNum = 2;
      } else if (multipleSelection.value[0].invoiceType == 3) {
        invtype.value = '差额票';
        invtypeNum.value = 3;
        ruleForm.value.invtypeNum = 3;
      }
      dialogVisible.value = true;
    } else {
      ElMessage.error("不同类型产品不能合并开票");
    }
    // dialogVisible.value = true
  }
};
// 查询商户指定产品类目
const invoiceTypeList = ref([]);
const wayinvoiceTypetypes = async () => {
  const billidse = fapiaoList.value.map((obj) => obj.id);

  const billid = billidse.join(',');
  const res = await invoiceTypetypes({
    proId: fapiaoList.value[0].proId,
    billIds: billid
  });
  invoiceTypeList.value = res.data;
};
// 提交表单
const rules = reactive({
  name: [{ required: true, message: '请输入收件人', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' },
  {
     pattern: /^1[3-9]\d{9}$/,
     message: '手机号格式不正确',
     trigger: 'blur',
   }],
  invtypeNum:[{ required: true, message: '请选择开票类型', trigger: 'blur' }],
  type: [{ required: true, message: '请选择开票类目', trigger: 'blur' }],
  address: [{ required: true, message: '请输入收件人地址', trigger: 'blur' }]
});

// 选择tabbal
const multipleSelection = ref([]); //选中的表格数据
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
//清除和全选
const handSelectAll = (rows) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTableRef.value!.toggleRowSelection(row, undefined);
    });
  } else {
    multipleTableRef.value!.clearSelection();
  }
};
// 服务费承担方
const syn_serviceChargeType = ref([
  {
    value: 1,
    label: '用工企业承担'
  },
  {
    value: 2,
    label: '自由职业者承担'
  }
]);
// 发票类型
const sys_normal_disable = ref([
  {
    value: 1,
    label: '增值税专用发票'
  },
  {
    value: 2,
    label: '增值税普通发票'
  },
  {
    value: 3,
    label: '差额票'
  }
]);
// 业务类型
const sys_busType_disable = ref([
  {
    value: 1,
    label: '委托代征'
  },
  {
    value: 2,
    label: '自然人代开'
  },
  {
    value: 3,
    label: '个体户注册'
  },
  {
    value: 4,
    label: '临时税务登记'
  },
  {
    value: 5,
    label: '资金代发'
  },
  {
    value: 6,
    label: '派遣&外包'
  }
]);

// tabbal列表数据
const loading = ref(false);
const invoiceBoll = ref([]);
const total = ref(0);
// 查询可代开数据列表
const waycanInvoicingList = async (event) => {
  if (event) queryParams.pageNum = 1;
  loading.value = true;
  let objdata = queryParams.value;
  objdata['params[syd_name]'] = objdata.syd_name || '';
  objdata['params[begin_time]'] = dateRange.value[0];
  objdata['params[end_time]'] = dateRange.value[1];
  const res = await canInvoicingList(queryParams.value);
  invoiceBoll.value = res.rows;
  total.value = res.total;
  loading.value = false;
  console.log('可代开数据列表', res);
};

onMounted(() => {
  waycanInvoicingList();
  wayinvoiceAddress();
});
</script>

<style lang="scss" scoped>
.ticletAppy {
  background-color: #eef0f3;
  .demo-pagination-block {
    padding-bottom: 15px;
    float: right;
  }
  .dialog-content {
    .dialog-content-box {
      background-color: #f8f8f8;
      padding: 15px 20px;
      display: flex;
      color: rgba(0, 0, 0, 0.65);
      font-size: 14px;
      & > div {
        flex: 1;
      }
    }
  }
  .invoice-info {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
    .infotext {
      font-size: 14px;
      margin-left: 20px;
      span {
        color: #409eff;
      }
    }
    a {
      font-size: 14px;
      margin-left: 20px;
    }
  }
  .messcolor {
    padding: 0px 0 0 30px;
    background: #e2f6ff;
    border: 1px solid #91d5ff;
    .ptext {
      font-size: 13px;
    }
  }
  .btn-nav {
    margin-left: 8px;
    & {
      color: #1890ff;
      text-decoration: none;
      background-color: transparent;
      outline: none;
      cursor: pointer;
      transition: color 0.3s;
    }
    .anticon {
      display: inline-block;
      color: inherit;
      font-style: normal;
      line-height: 0;
      text-align: center;
      text-transform: none;
      vertical-align: -0.125em;
      text-rendering: optimizeLegibility;
      -webkit-font-smoothing: antialiased;
    }
  }
  .card-header {
    border-bottom: 1px solid #e5e5e5;
    .one {
      width: 284px;
      color: #fff;
      background: #1890ff;
      text-align: center;
      font-size: 14px;
      font-weight: bold;
      padding: 10px 0;
      border-radius: 3px 3px 0 0;
    }
  }
}
</style>
